package com.onlyxiahui.wofa.server.socket.netty.tcp.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.onlyxiahui.framework.action.dispatcher.general.GeneralMessageHandler;
import com.onlyxiahui.wofa.server.net.core.session.SocketSessionHandler;
import com.onlyxiahui.wofa.server.socket.netty.common.handler.SessionDataHandler;
import com.onlyxiahui.wofa.server.socket.netty.tcp.session.ChannelSession;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class SocketHandler extends SimpleChannelInboundHandler<Object> {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	private SocketSessionHandler sessionHandler;
	private ChannelSession channelSession;
	private SessionDataHandler sessionDataHandler;

	public SocketHandler(GeneralMessageHandler messageHandler, SocketSessionHandler sessionHandler) {
		this.sessionHandler = sessionHandler;
		this.sessionDataHandler = new SessionDataHandler(sessionHandler, messageHandler);
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object frame) throws Exception {
		try {
			sessionDataHandler.message(channelSession, frame);
		} catch (Exception e) {
			sessionHandler.dataException(channelSession, frame, e);
			logger.error("", e);
		}
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		channelSession = new ChannelSession(ctx);
		if (logger.isDebugEnabled()) {
			String session = channelSession != null ? (channelSession.getRemoteAddress() + "/" + channelSession.getRemotePort()) : "";
			logger.debug("handlerAdded:" + session);
		}
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		sessionHandler.sessionRemove(channelSession);
		if (logger.isDebugEnabled()) {
			String session = channelSession != null ? (channelSession.getRemoteAddress() + "/" + channelSession.getRemotePort()) : "";
			String key = channelSession != null ? (channelSession.getKey()) : "";
			logger.debug("handlerRemoved:" + session + "/" + key);
		}
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("channelActive");
		}
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("channelInactive");
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// cause.printStackTrace();
		// ctx.close();
		logger.error("", cause);
	}
}
